<template>
  <div class="m-iselect">
    <span class="name">按省份选择：</span>
    <el-select
      v-model="pvalue"
      placeholder="省份">
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value"/>
    </el-select>
    <el-select
      v-model="cvalue"
      :disabled="!city.length"
      placeholder="城市">
      <el-option
        v-for="item in city"
        :key="item.value"
        :label="item.label"
        :value="item.value"/>
    </el-select>
    <span class="name">直接搜索：</span>
    <el-autocomplete
      v-model="keyword"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入内容"
      @select="handleSelect"
    />
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import { SET_POSITION } from '../../store/mutationTypes'

const { mapMutations } = createNamespacedHelpers('geo')
import _ from 'lodash'

export default {
  name: 'ISelect',
  props: {
    cities: {
      require: true,
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      pvalue: '',
      cvalue: '',
      keyword: '',
      province: [],
      city: []
    }
  },
  computed: {
    citys() {
      return this.cities.map(({ id, name, province }) => ({
        id,
        value: name,
        province
      }))
    }
  },
  watch: {
    async pvalue(nval) {
      const {
        status,
        data: { city }
      } = await this.$axios.get(`/geo/province/${nval}`)
      if (status == 200) {
        this.city = city.map(({ id, label }) => ({ value: id, label }))
      }
    }
  },
  async mounted() {
    const {
      status,
      data: { provinceList }
    } = await this.$axios.get('/geo/province')
    if (status == 200) {
      this.province = provinceList.map(({ id, label }) => ({
        value: id,
        label
      }))
    }
  },
  methods: {
    ...mapMutations({
      setPosition: SET_POSITION
    }),
    querySearchAsync: _.debounce(async function(key, cb) {
      cb(
        this.citys.filter(({ value }) => {
          return value.includes(key)
        })
      )
    }, 200),
    handleSelect(item) {
      this.setPosition({ province: item.province, city: item.value })
      this.$router.replace('/')
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/changeCity/iselect.scss';
</style>
